<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface TestItem {
  id: string;
  name: string;
  category: string;
  device: string;
  description: string;
  price: number;
}

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'success',items: TestItem[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref('');
const selectedCategory = ref('');
const selectedItems = ref<string[]>([]);

// 检验项目数据
const testItems = ref<TestItem[]>([
  // 血常规
  {
    id: '1',
    name: '血常规',
    category: 'blood',
    device: '血常规分析仪',
    description: '白细胞、红细胞、血小板计数等',
    price: 80,
  },
  {
    id: '2',
    name: '血细胞分类',
    category: 'blood',
    device: '血常规分析仪',
    description: '中性粒细胞、淋巴细胞等分类计数',
    price: 60,
  },
  {
    id: '3',
    name: '血红蛋白',
    category: 'blood',
    device: '血常规分析仪',
    description: '血红蛋白浓度测定',
    price: 40,
  },

  // 生化
  {
    id: '4',
    name: '血糖',
    category: 'biochemistry',
    device: '生化分析仪',
    description: '血糖浓度测定',
    price: 50,
  },
  {
    id: '5',
    name: '肝功能',
    category: 'biochemistry',
    device: '生化分析仪',
    description: 'ALT、AST、ALP等肝功能指标',
    price: 120,
  },
  {
    id: '6',
    name: '肾功能',
    category: 'biochemistry',
    device: '生化分析仪',
    description: 'BUN、肌酐等肾功能指标',
    price: 100,
  },
  {
    id: '7',
    name: '血脂',
    category: 'biochemistry',
    device: '生化分析仪',
    description: '胆固醇、甘油三酯等',
    price: 80,
  },

  // 电解质
  {
    id: '8',
    name: '钠离子',
    category: 'electrolyte',
    device: '电解质分析仪',
    description: '血清钠离子浓度',
    price: 40,
  },
  {
    id: '9',
    name: '钾离子',
    category: 'electrolyte',
    device: '电解质分析仪',
    description: '血清钾离子浓度',
    price: 40,
  },
  {
    id: '10',
    name: '氯离子',
    category: 'electrolyte',
    device: '电解质分析仪',
    description: '血清氯离子浓度',
    price: 40,
  },

  // 血气
  {
    id: '11',
    name: '血气分析',
    category: 'blood_gas',
    device: '血气分析仪',
    description: 'pH值、氧分压、二氧化碳分压',
    price: 150,
  },
  {
    id: '12',
    name: '血氧饱和度',
    category: 'blood_gas',
    device: '血气分析仪',
    description: '动脉血氧饱和度测定',
    price: 80,
  },

  // 显微镜
  {
    id: '13',
    name: '尿常规',
    category: 'microscope',
    device: '显微镜',
    description: '尿液常规检查',
    price: 60,
  },
  {
    id: '14',
    name: '粪便检查',
    category: 'microscope',
    device: '显微镜',
    description: '粪便常规检查',
    price: 50,
  },
  {
    id: '15',
    name: '细胞学检查',
    category: 'microscope',
    device: '显微镜',
    description: '细胞学涂片检查',
    price: 100,
  },
]);

// 计算属性
const filteredTestItems = computed(() => {
  let items = testItems.value;

  // 按类别筛选
  if (selectedCategory.value) {
    items = items.filter((item) => item.category === selectedCategory.value);
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    items = items.filter(
      (item) =>
        item.name.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword) ||
        item.device.toLowerCase().includes(keyword),
    );
  }

  return items;
});

const selectedTestItems = computed(() => {
  return testItems.value.filter((item) =>
    selectedItems.value.includes(item.id),
  );
});

// 方法
const getCategoryName = (category: string) => {
  const categoryMap: Record<string, string> = {
    blood: '血常规',
    biochemistry: '生化',
    electrolyte: '电解质',
    blood_gas: '血气',
    microscope: '显微镜',
  };
  return categoryMap[category] || category;
};

const toggleItemSelection = (item: TestItem) => {
  const index = selectedItems.value.indexOf(item.id);
  if (index === -1) {
    selectedItems.value.push(item.id);
  } else {
    selectedItems.value.splice(index, 1);
  }
};

const handleItemCheckboxChange = (item: TestItem, checked: boolean) => {
  if (checked) {
    if (!selectedItems.value.includes(item.id)) {
      selectedItems.value.push(item.id);
    }
  } else {
    const index = selectedItems.value.indexOf(item.id);
    if (index !== -1) {
      selectedItems.value.splice(index, 1);
    }
  }
};

const removeItem = (itemId: string) => {
  const index = selectedItems.value.indexOf(itemId);
  if (index !== -1) {
    selectedItems.value.splice(index, 1);
  }
};

const clearAll = () => {
  selectedItems.value = [];
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleCategoryChange = () => {
  // 类别筛选逻辑已在计算属性中处理
};

const handleConfirm = () => {
  if (selectedTestItems.value.length === 0) {
    message.warning('请选择至少一个检验项目');
    return;
  }

  emit('success', selectedTestItems.value);
  handleCancel();
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  searchKeyword.value = '';
  selectedCategory.value = '';
  selectedItems.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置状态
      searchKeyword.value = '';
      selectedCategory.value = '';
      selectedItems.value = [];
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="添加检验项目"
    width="800px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="test-item-modal">
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索检验项目"
          style="width: 300px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="selectedCategory"
          style="width: 150px"
          placeholder="选择类别"
          @change="handleCategoryChange"
        >
          <a-select-option value="">全部类别</a-select-option>
          <a-select-option value="blood">血常规</a-select-option>
          <a-select-option value="biochemistry">生化</a-select-option>
          <a-select-option value="electrolyte">电解质</a-select-option>
          <a-select-option value="blood_gas">血气</a-select-option>
          <a-select-option value="microscope">显微镜</a-select-option>
        </a-select>
      </div>

      <!-- 检验项目网格 -->
      <div class="test-grid">
        <div
          v-for="item in filteredTestItems"
          :key="item.id"
          class="test-card"
          :class="{ selected: selectedItems.includes(item.id) }"
          @click="toggleItemSelection(item)"
        >
          <div class="test-checkbox">
            <a-checkbox
              :checked="selectedItems.includes(item.id)"
              @change="(e) => handleItemCheckboxChange(item, e.target.checked)"
            />
          </div>
          <div class="test-info">
            <div class="test-name">{{ item.name }}</div>
            <div class="test-category">
              {{ getCategoryName(item.category) }}
            </div>
            <div class="test-device">{{ item.device }}</div>
            <div class="test-description">{{ item.description }}</div>
          </div>
        </div>
      </div>

      <!-- 已选择的项目 -->
      <div v-if="selectedTestItems.length > 0" class="selected-section">
        <div class="section-header">
          <h4>已选择的项目 ({{ selectedTestItems.length }})</h4>
          <a-button type="text" size="small" @click="clearAll">
            清空全部
          </a-button>
        </div>
        <div class="selected-list">
          <div
            v-for="item in selectedTestItems"
            :key="item.id"
            class="selected-item"
          >
            <span class="item-name">{{ item.name }}</span>
            <a-button
              type="text"
              size="small"
              danger
              @click="removeItem(item.id)"
            >
              ×
            </a-button>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          @click="handleConfirm"
          :disabled="selectedTestItems.length === 0"
        >
          确认添加 ({{ selectedTestItems.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.test-item-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.search-section {
  display: flex;
  gap: 16px;
  align-items: center;
}

.test-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: 400px;
  padding: 16px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.test-card {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.test-card:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.test-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.test-checkbox {
  margin-top: 2px;
  margin-right: 12px;
}

.test-info {
  flex: 1;
}

.test-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.test-category {
  display: inline-block;
  padding: 2px 6px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #1890ff;
  background: #e6f7ff;
  border-radius: 4px;
}

.test-device {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.test-description {
  font-size: 12px;
  line-height: 1.4;
  color: #999;
}

.selected-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.selected-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-item {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 6px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
}

.item-name {
  font-size: 12px;
  color: #333;
}

.modal-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}
</style>
